
//搜索用的数据
var DATA = {

    page : 1,

    per_page : 10,

    type : ''

};

//vue的data
var _Global_Data = {

    glass_type : {

        0 : '近视镜',

        1 : '太阳镜',

        2 : '功能镜'

    },                          //眼镜类型映射表

    type_name : {

        'Glass' : '镜框',

        'Lens' : '镜片',

        'BeautyContactLens' : '彩色隐形眼镜',

        'TransparentContactLens' : '透明隐形眼镜',

        'NursingSupply' : '护理用品'

    },                           //眼镜的分类名字

    query_info : DATA,      //查询所需要的数据

    search_info : {},       //用于接受查询数据

    all_products : {},           //全部现有的商品

    current_glass_type : '',     //当前选择的主商品类型

    current_glass_id : '',       //当前选择的主商品id

    current_products : [],       //当前主商品列表

    combine_products : [],       //新增组合镜片数组

    current_combines : [],        //当前商品对应的现有搭配镜片数组

    combine_detail : {},           //当前查看的组合商品详情

    combine_list : {},             //已有组合商品的商品信息

    is_provider : false,        //是否是虚拟仓权限登录

    sup_product : null           //用于承接供应商返回的全部商品

};

//全部商品
var AllProductResource = new Resource( API_LIST.ALL_PRODUCT_LIST , Vue.http );
//搭配商品
var CombineProductResource = new Resource( API_LIST.COMBINE_PRODUCT , Vue.http );
//请求颜色
var ProductColorResource = new Resource( API_LIST.COMBINE_COLOR , Vue.http);

!function glassControl(){

    Vue.directive('min-value', {
        bind : function (el,binding) {

            el.handler = function () {

                var min_value = binding.value;
                var int_value = parseInt(el.value);

                if ( int_value !== int_value ) {
                    el.value = 0;
                } else if ( int_value < min_value ) {
                    el.value = min_value;
                } else {
                    el.value = int_value;
                }

            };

            el.addEventListener('input', el.handler );
            el.addEventListener('blur', el.handler );
        },
        unbind : function (el) {

            el.removeEventListener('input', el.handler);
            el.removeEventListener('blur', el.handler);
        }
    });

     var vm = new Vue({

        el: "#dashboard",

        data: _Global_Data,

        created : function(){

            this.initGlassData();

            this.allCombineProduct();

            if( sessionStorage.getItem('login_customer_type') == 1 ){

                this.is_provider = true;

            }

        },

        methods: {
            //改变页数的时候出发的函数
            pageChange : function pageChange(val){

                this.search_info.page = val;

                this.search_info.per_page = this.query_info.per_page;

                this.allCombineProduct(this.search_info);

            },
            //改变每页显示数时触发的函数
            sizeChange : function sizeChange(val){

                this.search_info.per_page = val;

                this.query_info.per_page = val;

                this.allCombineProduct(this.search_info);

            },
            //总价
            totalPrice : function totalPrice( index ){

                if( this.combine_products[index].goods_type == 'TransparentContactLens' ||
                    this.combine_products[index].goods_type == 'Lens' ||
                    this.combine_products[index].goods_type == 'BeautyContactLens'){

                    var total_price = parseInt(this.combine_products[index].left_count) + parseInt(this.combine_products[index].right_count);

                    return total_price*this.combine_products[index].sale_price;

                }else {

                    return this.combine_products[index].count*this.combine_products[index].sale_price;

                }
            },
            //选取主商品类型
            getValue : function getValue( e ){

                this[e.target.dataset.name] = e.target.value;

            },

            //模态框里select2获取value
            getCombineValue : function getCombineValue( e ){

                this.combine_detail[e.target.dataset.name] = e.target.value;

            },

            //组合镜片中获取customer_type的方法
            getCustomerType : function getCustomerType( index , e){

                this.combine_products[index].customer_type = e.target.value;

                this.productTypeFilter( e.target.value,this.combine_products[index] , '#product_single' );

                this.$nextTick(function(){

                    $('.product_type').eq(2*index+1).val('').trigger('change');

                    $('.relate_product').eq(2*index+1).val('').trigger('change');

                    $('.relate_product_color').eq(2*index+1).val('').trigger('change');

                });

            },

            //组合镜片中获取product_type的方法
            getRelateType : function getRelateType( index , e ){

                this.combine_products[index].goods_type = e.target.value;

                this.combine_products[index].current_product = this.combine_products[index].current_product_all[e.target.value];

                if( this.combine_products[index].goods_type == 'TransparentContactLens' ||
                    this.combine_products[index].goods_type == 'NursingSupply'){

                    this.combine_products[index].color_id = null;

                }

                $('.relate_product').eq(2*index+1).val('').trigger('change');

                $('.relate_product_color').eq(2*index+1).val('').trigger('change');

            },

            //组合镜片中获取relate_product的方法
            getRelateProduct : function getRelateProduct( index , e ){

                this.combine_products[index].goods_id = e.target.value;

                $('.relate_product_color').eq(2*index+1).val('').trigger('change');

                this.productSelectPublic( e.target.value , this.combine_products[index] );

                if( this.combine_products[index].goods_type == 'TransparentContactLens' ||
                    this.combine_products[index].goods_type == 'NursingSupply')return;

                this.combineGlassColor( this.combine_products[index] , '#product_single' );

            },

            //组合镜片中获取color_id的方法
            getColorId : function getColorId( index , e ){

                this.combine_products[index].color_id = e.target.value;

            },

            //组合镜片过滤出可选的product_type的共有方法
            productTypeFilter : function productTypeFilter( value , object , form ){

                var self = this;

                object.current_product_type = [];

                if( parseInt(value) === 1 ){

                    var params = {

                        customer_type : 1

                    };

                    if( self.sup_product ){

                        var json_object = JSON.stringify(self.sup_product);

                        object.current_product_all = JSON.parse(json_object);

                        for( var key in object.current_product_all ){

                            if( object.current_product_all[key].length > 0 ){

                                object.current_product_type.push(key);

                            }

                        }

                    }else {

                        self.combineGlassType( form , params )
                            .then(function(){

                                var json_object = JSON.stringify(self.sup_product);

                                object.current_product_all = JSON.parse(json_object);

                                for( var key in object.current_product_all ){

                                    if( object.current_product_all[key].length > 0 ){

                                        object.current_product_type.push(key);

                                    }

                                }

                            })

                    }

                }else {

                    var json_object = JSON.stringify(self.all_products);

                    object.current_product_all = JSON.parse(json_object);

                    for( var key in object.current_product_all ){

                        if( object.current_product_all[key].length > 0 ){

                            object.current_product_type.push(key);

                        }

                    }

                }

            },

            //组合镜片过滤出对应价格的共有方法
            productSelectPublic : function productSelectPublic( value , object ){

                if( object.current_product ){

                    var selected_product = object.current_product.filter(function(product){

                        return product.id == value;

                    })[0];

                    object.sale_price = selected_product.promotion_sale_price;

                }

            },

            //增加组合镜片的方法
            newProductAdd : function newProductAdd(){

                var new_product = {

                    customer_type : null,

                    goods_type : null,

                    goods_id : null,

                    color_id : null,

                    sale_price : null,

                    count : 1,

                    left_count : 1,

                    right_count : 1,

                    max_count : null,

                    current_product_all : {},

                    current_product : null,

                    current_product_type : [],

                    current_colors : []
                };

                this.combine_products.push( new_product );

            },

            //增加与上一个组合商品一样但不同颜色的商品
            newColorProduct : function newColorProduct(){

                var last_index = this.combine_products.length - 1;

                var same_product = JSON.parse(JSON.stringify(this.combine_products[last_index]));

                var trash_color = same_product.current_colors.indexOf(this.combine_products[last_index].color_id);

                same_product.current_colors.splice(trash_color,1);

                this.combine_products.push(same_product);

            },

            //删除组合镜片的方法
            lensDelete : function lensDelete(){

                this.combine_products.pop();

            },

            //组合镜片切换请求虚拟仓商品类别的方法
            combineGlassType : function combineGlassType( form , params ){

                var self = this;

                App.blockUI(form);

                return AllProductResource.index(params)
                                        .then(function (res) {

                                            if (parseInt(res.data.code) === 0) {

                                                self.sup_product = res.data.all_products;

                                            } else {

                                                alert(res.data.error);

                                            }

                                            App.unblockUI(form);

                                        })
                                        .catch(function (err) {

                                            console.log(err);

                                            App.unblockUI(form);

                                            alert('网络异常！');

                                        })

            },

            //组合镜片选择商品请求对应的颜色的方法
            combineGlassColor : function combineGlassColor( object , form ){

                var params = {

                    product_id : object.goods_id,

                    product_type : object.goods_type

                };

                App.blockUI(form);

                return ProductColorResource.index( params )
                                            .then(function (res) {

                                                if (parseInt(res.data.code) === 0) {

                                                    object.current_colors = res.data.colors;

                                                } else {

                                                    alert(res.data.error);

                                                }

                                                App.unblockUI(form);

                                            })
                                            .catch(function (err) {

                                                console.log(err);

                                                App.unblockUI(form);

                                                alert('网络异常！');

                                            })

            },

            //保存组合商品信息
            combineProductSave : function combineProductSave(){

                var self = this;

                if( self.combine_products.length == 0 ){

                    alert('没有选择搭配商品！');

                    return;

                }

                for( var i=0;i<self.combine_products.length;i++ ){

                    if( !self.combine_products[i].customer_type ){

                        alert('没有选择商品来源！');

                        return;

                    }else {

                        if( !self.combine_products[i].goods_type ){

                            alert('没有选择商品类型！');

                            return;

                        }else {

                            if( !self.combine_products[i].goods_id ){

                                alert('没有选择商品！');

                                return;

                            }else {

                                if( !self.combine_products[i].color_id ){

                                    alert('没有选择颜色！');

                                    return;

                                }

                            }

                        }

                    }

                }

                App.blockUI('#product_single');

                delete self.combine_products.current_product_all;
                delete self.combine_products.current_product;
                delete self.combine_products.current_product_type;
                delete self.combine_products.current_colors;

                var params = {

                    product_id : self.current_glass_id,

                    product_type : self.current_glass_type,

                    relate_products : self.combine_products

                };

                CombineProductResource.store( params )
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            alert('保存成功！');

                                            self.combine_products = [];

                                            self.getGlassList();

                                        } else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#product_single');

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        App.unblockUI('#product_single');

                                        alert('网络异常！');

                                    })

            },
            
            //查看已有组合商品的所有商品
            allCombineProduct : function allCombineProduct(params){

                var self = this;

                App.blockUI('#combine_list_form');

                CombineProductResource.create(params)
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            self.combine_list = res.data.products;

                                            self.combine_list.per_page = parseInt(self.combine_list.per_page);

                                        } else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#combine_list_form');

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        App.unblockUI('#combine_list_form');

                                        alert('请求api失败！');

                                    })
            },

            //查看某一组合商品的信息
            combineProductDetail : function combineProductDetail(id){

                var self = this;

                self.combine_detail = {};

                self.editing = true;

                App.blockUI('#editor-form');

                CombineProductResource.edit(id)
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            res.data.relate_product.current_product_all = {};

                                            res.data.relate_product.current_product = null;

                                            res.data.relate_product.current_product_type = [];

                                            res.data.relate_product.current_colors = [];

                                            self.combine_detail = res.data.relate_product;

                                        } else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#editor-form');

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        App.unblockUI('#editor-form');

                                        alert('网络异常！');

                                    })

            },

            //删除组合商品信息
            combineProductDelete : function combineProductDelete(id){

                var self = this;

                App.blockUI('#combine_form');

                CombineProductResource.destroy(id)
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            alert('删除成功！');

                                            self.getGlassList();

                                        } else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#combine_form');

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        App.unblockUI('#combine_form');

                                        alert('网络异常！');

                                    })

            },

            //修改组合商品信息
            combineProductRevise : function combineProductRevise(){

                var self = this;

                App.blockUI('#editor-form');

                var params = {

                    _method : 'put',

                    goods_type : self.combine_detail.goods_type,

                    goods_id : self.combine_detail.goods_id,

                    color_id : self.combine_detail.color_id,

                    sale_price : self.combine_detail.sale_price,

                    count : parseInt(self.combine_detail.count),

                    left_count : parseInt(self.combine_detail.left_count),

                    right_count : parseInt(self.combine_detail.right_count),

                    max_count : self.combine_detail.max_count

                };

                CombineProductResource.revise( self.combine_detail.id , params)
                                    .then(function(res){

                                        if( parseInt(res.data.code) === 0 ){

                                            self.getGlassList();

                                            $('.modal-footer > a').trigger('click');

                                        }else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#editor-form');

                                    })
                                    .catch(function(err){

                                        console.log(err);

                                        App.unblockUI('#editor-form');

                                        alert('网络异常，请重试！');

                                    })

            },

            //获取现有眼镜列表
            getGlassList : function getGlassList(){

                var self = this;

                var params = {

                    product_id : this.current_glass_id,

                    product_type : this.current_glass_type

                };

                App.blockUI('#combine_form');

                CombineProductResource.index( params )
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            self.current_combines = res.data.relate_product_list;

                                        } else {

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#combine_form');

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        App.unblockUI('#combine_form');

                                        alert('网络不稳定，请刷新重试！');

                                    })

            },

            //初始化获得需要的数据
            initGlassData : function initGlassData( params ){

                var self = this;

                App.blockUI('#product_single');

                return AllProductResource.index( params )
                                        .then(function (res) {

                                            if (parseInt(res.data.code) === 0) {

                                                self.all_products = res.data.all_products;

                                                self.current_glass_type = 'Glass';

                                                $('.main_type').val('Glass').trigger('change');

                                            } else {

                                                alert(res.data.error);

                                            }

                                            App.unblockUI('#product_single');

                                        })
                                        .catch(function (err) {

                                            console.log(err);

                                            App.unblockUI('#product_single');

                                            alert('网络不稳定，请刷新重试！');

                                        })

            }

        },
        watch : {
            // 监听组合镜片的变化
            combine_products : function (){

                setTimeout(function(){

                    $('.combine-products').each( function(){
                        $(this).find('select').select2();
                    });

                },30);

            },
            // 监听商品类型
            current_glass_type : function (){

                // var self = this;

                this.current_products = this.all_products[this.current_glass_type];

                this.current_glass_id = this.current_products[0].id;

                this.$nextTick(function(){

                    $('.main_product').val(this.current_products[0].id).trigger('change');

                });

            },
            // 监听主商品
            current_glass_id : function (){

                this.getGlassList();

            },
            //监听模态框中的来源选择
            'combine_detail.customer_type' : function(){

                this.productTypeFilter( this.combine_detail.customer_type , this.combine_detail , '#editor-form' );

                this.$nextTick(function(){

                    $('.modal_customer_type').val(this.combine_detail.customer_type).trigger('change');

                });

            },
            //监听模态框中的类型选择
            'combine_detail.goods_type' : function(){

                this.combine_detail.current_product = this.combine_detail.current_product_all[this.combine_detail.goods_type];

                this.$nextTick(function(){

                    $('.modal_goods_type').val(this.combine_detail.goods_type).trigger('change');

                });

                if( this.combine_detail.goods_type == 'TransparentContactLens' ||
                    this.combine_detail.goods_type == 'NursingSupply'){

                    this.combine_detail.color_id = null;

                }

            },
            //监听模态框中的商品选择
            'combine_detail.goods_id' : function(){

                var self = this;

                // self.productSelectPublic( self.combine_detail.goods_id , self.combine_detail );

                this.$nextTick(function(){

                    $('.modal_relate_product').val(self.combine_detail.goods_id).trigger('change');

                });

                if( self.combine_detail.goods_type == 'TransparentContactLens' ||
                    self.combine_detail.goods_type == 'NursingSupply')return;

                if( !self.combine_detail.goods_id )return;

                self.combineGlassColor( self.combine_detail , '#editor-form' )
                    .then(function(){

                        $('.modal_relate_color').val(self.combine_detail.color_id).trigger('change');

                    });

            }
        }

    });

}();